﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Xml;

namespace mqtt_app
{
     struct _sever_data_frame
    {
        public byte[] start_tag;

        public UInt16 protocol_type;
        public UInt32 Dev_Add;
        public UInt16 Dev_type;
        public byte Interaction_tag;
        public UInt16 data_len;
        public byte Cmd;

        public byte[] data_table;
        public byte crc_sum8;
    }    ;
     struct attribute_structx
    {
        public UInt16 att_num;
        public string att_name;
        public byte[] att_data;
    };
    public partial class Form4 : Form
    {
        private TcpListener tcpListener;
        private Thread listenThread;
        DataTable dt_dev_type;
        DataTable dt_attr;

        
        Encoding utf8 = Encoding.GetEncoding("UTF-8");
        Encoding gb2312 = Encoding.GetEncoding("GB2312");
        string[] dev_tpey_str = { "无效类型","定位手环2G","海上腕表","海上定位肩章","",
            "","","","","","","","","","","","定位通信基站"};
        string[] start_type_str = { "无效类型", "上电启动", "软件重启", "看门狗重启","断网重连" };
        string[] att_str = { "定位手环2G", "海上腕表", "海上定位肩章" };
        public Form4()
        {
            
            InitializeComponent();
        }
        /// <summary>
        /// 字节数组转16进制字符串：空格分隔
        /// </summary>
        /// <param name="byteDatas"></param>
        /// <returns></returns>
        private string ToHexStrFromByte( byte[] byteDatas,int nums)
        {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < nums; i++)
            {
                builder.Append(string.Format("{0:X2} ", byteDatas[i]));
            }
            return builder.ToString().Trim();
        }
       
        /// <summary>
        ///  根据指定的地址获取xml文件进行转换 文件地址
        /// </summary>
        /// <param name="xmlPath"></param>
        /// <returns></returns>
        private DataTable ConvertXMLToDataDataTable(string xmlPath)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                //根据地址加载Xml文件  
                xmldoc.Load(xmlPath);
                DataTable dt = new DataTable();
                stream = new StringReader(xmldoc.InnerXml);
                reader = new XmlTextReader(stream);
                dt.ReadXml(reader);
                return dt;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (reader != null)
                    reader.Close();
                if (stream != null)
                    stream.Close();
            }
        }
        private void Form4_Load(object sender, EventArgs e)
        {
            string pathname;
            pathname = AppDomain.CurrentDomain.BaseDirectory + "main.xml";
            dt_dev_type = ConvertXMLToDataDataTable(pathname);
            comboBox2.DataSource = dt_dev_type;
            comboBox2.DisplayMember = "类型";
            comboBox2.ValueMember = "类型ID";

            pathname = AppDomain.CurrentDomain.BaseDirectory + "attribute.xml";
            dt_attr = ConvertXMLToDataDataTable(pathname);
            comboBox4.DataSource = dt_attr;
            comboBox4.DisplayMember = "说明";
            comboBox4.ValueMember = "属性ID";
        }
        private void OutMsg(RichTextBox rtb, string msg, Color color)
        {
            rtb.Invoke(new EventHandler(delegate
            {
                rtb.SelectionStart = rtb.Text.Length;//设置插入符位置为文本框末
                rtb.SelectionColor = color;//设置文本颜色
                rtb.AppendText(msg + "\r\n");//输出文本，换行
                rtb.ScrollToCaret();//滚动条滚到到最新插入行
            }));
        }
        private void Server_start(string ip,int port)
        {
            IPAddress severip = IPAddress.Parse(ip);
            int severport = port;
            this.tcpListener = new TcpListener(severip, severport);
            this.listenThread = new Thread(new ThreadStart(ListenForClients));
            this.listenThread.Start();
            OutMsg(richTextBox1, "Server started at:[" + severip.ToString()+": "+ severport .ToString()+ "]  @" + DateTime.Now.ToString() + "\r\n", Color.Green);
            Console.WriteLine("Server started at {0} :{1} @ {2}", severip, severport, DateTime.Now.ToString());
        }


        private void ListenForClients()
        {
            this.tcpListener.Start();

            while (true)
            {
                //blocks until a client has connected to the server
                TcpClient client = this.tcpListener.AcceptTcpClient();

                //create a thread to handle communication 
                //with connected client
                Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
                clientThread.Start(client);
            }
        }


        private void HandleClientComm(object client)
        {
            TcpClient tcpClient = (TcpClient)client;
            OutMsg(richTextBox1, "Client:[" + tcpClient.Client.LocalEndPoint.ToString() + "] connected @" + DateTime.Now.ToString() + "\r\n", Color.Green);
            Console.WriteLine("Client @[{0}] connected @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());

            NetworkStream clientStream = tcpClient.GetStream();

            byte[] message = new byte[4096];
            int bytesRead = 0;
            //bool isRight=false;

            while (true)
            {
                bytesRead = 0;

                try
                {
                    //blocks until a client sends a message
                    bytesRead = clientStream.Read(message, 0, 4096);
                }
                catch
                {
                    //a socket error has occured
                    OutMsg(richTextBox1, "Error: receive msg error\r\n", Color.Green);
                    Console.WriteLine("Error:receive msg error");
                    break;
                }

                if (bytesRead == 0)
                {
                    //the client has disconnected from the server
                    OutMsg(richTextBox1, "Client:[" + tcpClient.Client.LocalEndPoint.ToString() + "] disconnect @" + DateTime.Now.ToString() + "\r\n", Color.Green);
                    Console.WriteLine("Client @[{0}] disconnect @{1}", tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
                    break;
                }
                Console.WriteLine("Recv [{0}]", bytesRead);
                //for(int i=0;i<bytesRead;i++)
                //{
                //    Console.WriteLine(message[i]);
                //}
                string rec_data = ToHexStrFromByte(message,bytesRead );
                OutMsg(richTextBox1, "Recv:[" + tcpClient.Client.LocalEndPoint.ToString() + "]:msg:@[" + rec_data + "] @" + DateTime.Now.ToString() + "\r\n", Color.BlueViolet);
                Console.WriteLine(rec_data);
                if (data_frame_check(message, bytesRead))
                {
                    Sever_data_process( clientStream,message, bytesRead);
                }
                //message has successfully been received
                ASCIIEncoding encoder = new ASCIIEncoding();
                //System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
                /*
                string recvstr = encoder.GetString(message, 0, bytesRead);
                OutMsg(richTextBox1, "Recv:[" + tcpClient.Client.LocalEndPoint.ToString() + "]:msg:@[" + recvstr + "] @" + DateTime.Now.ToString() + "\r\n", Color.Green);
                Console.WriteLine("Recv:[{1}]:msg:@[{0}] @{2}", recvstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());

                //send msg to client
                string sendstr = "Server OK";
                if (recvstr == "101")
                {
                    //isRight = true;
                    sendstr = "202";
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.White;
                }

                byte[] buffer = encoder.GetBytes(sendstr);
                clientStream.Write(buffer, 0, buffer.Length);
                clientStream.Flush();
                OutMsg(richTextBox1, "Sent:[" + tcpClient.Client.LocalEndPoint.ToString() + "]:msg:@[" + sendstr + "] @" + DateTime.Now.ToString() + "\r\n", Color.Green);
                //Console.WriteLine("Sent:["+tcpClient.Client.LocalEndPoint.ToString()+"]:msg:@["+ sendstr + "] @"+ DateTime.Now.ToString() + "\r\n", sendstr, tcpClient.Client.LocalEndPoint, DateTime.Now.ToString());
                */
                }

            //tcpClient.Close();
        }
        private bool data_frame_check(byte[] data,int data_len)
        {
            byte sum;
            byte checksum =0;
            string debug_str = "";
            for (int i = 0; i < data_len; i++)
            {
                if ((data[i] == 0x24)&& (data[i+1] == 0x24))
                {
                    if ((data[data_len - 1] == 0x35) && (data[data_len - 1] == 0x35))
                    {
                        sum = data[data_len - 3];
                        for (int k = i + 3; k < data_len - 3; k++)
                            checksum += data[k];
                        debug_str = String.Format("\r\n接收到的校验：0x{0:X2}；计算校验结果：0x{1:X2}", sum, checksum);
                        OutMsg(richTextBox1,debug_str,Color.Green);
                        Console.WriteLine(debug_str);
                        if(sum==checksum)
                        {
                            OutMsg(richTextBox1, "校验通过", Color.Green);
                            return true;
                        }
                        else
                        {
                            OutMsg(richTextBox1, "校验失败", Color.Red);
                            return false;
                        }
                        
                    }
                }
            }
            return false;
        }
        private DateTime GetDateTime(int timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = ((long)timeStamp * 10000000);
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime targetDt = dtStart.Add(toNow);
            return targetDt;
        }
        int attribute_get(byte[] data, int data_len)
        {
            attribute_structx[] att_frame = new attribute_structx[10];
            int att_total = 0;
            int count = 0;
            int i;
            int k;
            int temp = 0;
            UInt32 time_temp = 0;
            att_total = data[0];
            count = 1;
            string debug_str = "";
            DateTime _date_time;
            int msg_id=0;
            debug_str = "属性对个数：" + att_total.ToString();
            OutMsg(richTextBox1, debug_str, Color.Green);
            Console.WriteLine(debug_str);
            for (i = 0; i < att_total; i++)
            {
                att_frame[i].att_num = (ushort) data[count ++];
                
                switch (att_frame[i].att_num)
                {
                  
                    case 0x02:	//软件版本
                        att_frame[i].att_data = new byte[3];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        //int temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        debug_str = String.Format("软件版本 {2:d}.{1:d}.{0:d}", att_frame[i].att_data[0], att_frame[i].att_data[1], att_frame[i].att_data[2]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x03:	//硬件版本
                        att_frame[i].att_data = new byte[3];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        debug_str = String.Format("硬件版本 {2:d}.{1:d}.{0:d}", att_frame[i].att_data[0], att_frame[i].att_data[1], att_frame[i].att_data[2]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str); 
                        break;
                    case 0x04:	//电池电量
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        temp = BitConverter.ToUInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("电池电量 {0:F} %", temp*0.1);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x05:	//电池电压
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                         temp = BitConverter.ToUInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("电池电压 {0:d}mV", temp );
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);

                        break;
                    case 0x06:	//启动类型
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];
                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("启动类型：{0}", start_type_str[temp]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        

                        break;
                   
                    case 0x11:	//心率
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        temp = BitConverter.ToUInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("心率：{0}", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        

                        break;
                    case 0x12:	//步数
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        temp = BitConverter.ToUInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("步数：{0}", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);

                        break;
                    case 0x13:	//定位类型
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];
                        
                        temp = BitConverter.ToUInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("定位类型：{0}", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);

                        break;
                    case 0x15:	//经度
                        att_frame[i].att_data = new byte[12];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];
                        att_frame[i].att_data[4] = data[count++];
                        att_frame[i].att_data[5] = data[count++];
                        att_frame[i].att_data[6] = data[count++];
                        att_frame[i].att_data[7] = data[count++];
                        att_frame[i].att_data[8] = data[count++];
                        att_frame[i].att_data[9] = data[count++];
                        att_frame[i].att_data[10] = data[count++];
                        att_frame[i].att_data[11] = data[count++];
                        //temp = BitConverter.ToInt16(att_frame[i].att_data, 0);
                        debug_str = "经度：" + gb2312.GetString(att_frame[i].att_data);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                       

                        break;
                    case 0x17:	//纬度
                        att_frame[i].att_data = new byte[11];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];
                        att_frame[i].att_data[4] = data[count++];
                        att_frame[i].att_data[5] = data[count++];
                        att_frame[i].att_data[6] = data[count++];
                        att_frame[i].att_data[7] = data[count++];
                        att_frame[i].att_data[8] = data[count++];
                        att_frame[i].att_data[9] = data[count++];
                        att_frame[i].att_data[10] = data[count++];

                        //temp = BitConverter.ToInt16(att_frame[i].att_data, 0);
                        debug_str = "纬度：" + gb2312.GetString(att_frame[i].att_data);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x20:	//定位时间
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        _date_time = GetDateTime(temp);
                        debug_str = String.Format("定位时间：{0} {1}", temp, _date_time);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        
                        break;
                    case 0x21:	//上报时间
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        time_temp = BitConverter.ToUInt32(att_frame[i].att_data, 0);
                        _date_time = GetDateTime((int)time_temp);
                        msg_id = (int)time_temp;
                        debug_str = String.Format("上报时间：{0} {1}", time_temp, _date_time);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x22:	//上报频率
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        

                        temp = BitConverter.ToInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("上报频率：{0} s", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x24:	//报警类型
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];



                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("报警类型：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x26:	//充电状态
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];


                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("充电状态：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x29:	//服务器IP
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        debug_str = String.Format("监控中心：{0}.{1}.{2}.{3}", att_frame[i].att_data[0], att_frame[i].att_data[1], att_frame[i].att_data[2], att_frame[i].att_data[3]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    
                    case 0x30:	//端口
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];

                        temp = BitConverter.ToInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("监控中心端口：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x34:	//服务器IP
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        debug_str = String.Format("定位引擎：{0}.{1}.{2}.{3}", att_frame[i].att_data[0], att_frame[i].att_data[1], att_frame[i].att_data[2], att_frame[i].att_data[3]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;

                    case 0x35:	//端口
                        att_frame[i].att_data = new byte[2];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];

                        temp = BitConverter.ToInt16(att_frame[i].att_data, 0);
                        debug_str = String.Format("定位引擎端口：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x36:	//服务器IP
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        debug_str = String.Format("基站IP：{0}.{1}.{2}.{3}", att_frame[i].att_data[0], att_frame[i].att_data[1], att_frame[i].att_data[2], att_frame[i].att_data[3]);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x37:	//自检消息
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("自检消息：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x38:	//设备控制响应
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("设备控制响应：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x31:	//msg_id
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];
                        temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        debug_str = String.Format("msg_id：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x32:	//数据帧状态
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("数据帧状态：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x33:	//ACK命令
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str =  String.Format("ACK命令： {0:X2} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x42:	//uwb定位信息
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];
                        temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        debug_str = String.Format("uwb定位信息： {0:X8} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x43:	//同步时间
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];

                        temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        _date_time = GetDateTime(temp);
                        debug_str = String.Format("同步时间：{0} {1}", temp, _date_time);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x44:	//目标设备类型
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("目标设备类型：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x45:	//UWB工作模式
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("定位通信基站工作模式：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x46:	//NFC信息
                        att_frame[i].att_data = new byte[4];
                        att_frame[i].att_data[0] = data[count++];
                        att_frame[i].att_data[1] = data[count++];
                        att_frame[i].att_data[2] = data[count++];
                        att_frame[i].att_data[3] = data[count++];
                        temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        debug_str = String.Format("NFC信息：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x50:	//短消息
                        att_frame[i].att_data = new byte[32];
                        for (k = 0; k < 32; k++)
                            att_frame[i].att_data[k] = data[count++];
                        //temp = BitConverter.ToInt32(att_frame[i].att_data, 0);
                        debug_str = String.Format("短消息：{0} ", gb2312.GetString(att_frame[i].att_data));
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        OutMsg(richTextBox1, "", Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    case 0x51:  //消息回执
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];
                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("消息回执：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        break;
                    case 0x60:	//UWB工作模式
                        att_frame[i].att_data = new byte[1];
                        att_frame[i].att_data[0] = data[count++];

                        temp = (int)att_frame[i].att_data[0];
                        debug_str = String.Format("设备控制：{0} ", temp);
                        OutMsg(richTextBox1, debug_str, Color.Green);
                        Console.WriteLine(debug_str);
                        break;
                    default:
                        break;
                }
            }
            for (i = 0; i < att_total; i++)
            {
                //printf("%s att_num:0x%04x att_data:", (att_frame[i].att_name), att_frame[i].att_num);

                //printf("\r\n");
            }
            return msg_id;
        }
        private void build_ack(NetworkStream clientStream, _sever_data_frame data, byte cmd,int msg_id)
        {
           
            
            byte dev_mode;
            UInt16 data_lenth;
            byte comond;
            
            byte check_sum = 0;
            byte[] end = { 0x35, 0x35 };
            byte[] data_frame = new byte[1024];
            UInt32 index = 0;
            DataRow dr = dt_dev_type.Rows[comboBox2.SelectedIndex];
            Console.WriteLine(dr["类型ID"].ToString());
            dev_mode = (byte)Convert.ToUInt32(dr["类型ID"].ToString(), 16);
            data_unit_index = 0;
            build_att_frame_index = 0;
            build_att_frame_index = 0;
            add_att(0x32, "1", "数据帧状态");
            add_att(0x33, cmd.ToString(), "ACK命令");
            add_att(0x31, msg_id.ToString(), "msg_id");
            data_frame[index++] = 0x24;
            data_frame[index++] = 0x24;
            data_frame[index++] = 0x01;
            data_frame[index++] = (byte)(data.Dev_Add);
            data_frame[index++] = (byte)(data.Dev_Add >> 8);
            data_frame[index++] = (byte)(data.Dev_Add >> 16);
            data_frame[index++] = (byte)(data.Dev_Add >> 24);
            data_frame[index++] = (byte)data.Dev_type;//设备类型
            data_frame[index++] = (byte)(data_unit_index + 1);//数据单元长度
            data_frame[index++] = (byte)(data_unit_index >> 8);
            data_frame[index++] = (byte)(0x01);//命令
            data_frame[index++] = (byte)(build_att_frame_index);//属性对个数
            for (int i = 0; i < data_unit_index; i++)
            {
                data_frame[index++] = data_unit[i];
            }
            UInt32 check_end = index;
            for (int k = 3; k < check_end; k++)
            {
                check_sum += data_frame[k];
            }
            data_frame[index++] = (byte)(check_sum);
            data_frame[index++] = (byte)(0x35);
            data_frame[index++] = (byte)(0x35);
            string data_frame_str = "";
            for (int i = 0; i < index; i++)
            {
                data_frame_str += String.Format("{0:X2} ", data_frame[i]);
            }
            Console.WriteLine(data_frame_str);
            OutMsg(richTextBox2, "生成ACK包:" + data_frame_str, Color.BlueViolet);
            if (clientStream != null)
            {
                OutMsg(richTextBox1, "Sent ACK:[" + "" + "]:msg:@[" + data_frame_str + "] @" + DateTime.Now.ToString() + "\r\n", Color.BlueViolet);
                clientStream.Write(data_frame, 0, (int)index);
                clientStream.Flush();
            }
            if (data_frame_check(data_frame, (int)index))
            {
                Sever_data_process(null,data_frame, (int)index);
            }
            
        }
        private void Sever_data_process(NetworkStream clientStream, byte[] data,int data_len)
        {
            int i;
            int msg_id = 0;
            string debug_srt = "";
            _sever_data_frame data_frame=new _sever_data_frame { };
            data_frame.data_table = new byte[1024];
            data_frame.protocol_type = (ushort)((UInt16)data[1] << 8 | (UInt16)data[2]);
            data_frame.Dev_Add = (UInt32)data[6] << 24 | (UInt32)data[5] << 16 | (UInt32)data[4] << 8 | (UInt32)data[3];
            
            data_frame.Dev_type = (ushort)(data[7] );
            
            //data_frame.Interaction_tag = data[10];
            data_frame.data_len = (ushort)((UInt16)data[9] << 8 | (UInt16)data[8]);
            data_frame.Cmd = data[10];

            for (i = 0; i < data_frame.data_len; i++)
                data_frame.data_table[i] = data[i + 11];
            //	for(i=0;i<data_frame.data_len;i++)
            //		printf("0x%02x ",data_frame.data_table[i]);
            debug_srt = String.Format("设备地址： {0:X8} ", data_frame.Dev_Add);
            OutMsg(richTextBox1,debug_srt,Color.Green);
            Console.WriteLine(debug_srt);
            debug_srt = "设备类型：" + dev_tpey_str[data_frame.Dev_type];
            OutMsg(richTextBox1, debug_srt, Color.Green);
            Console.WriteLine(debug_srt);
            debug_srt = "数据单元长度：" + data_frame.data_len;
            OutMsg(richTextBox1, debug_srt, Color.Green);
            Console.WriteLine(debug_srt);
            debug_srt = "命令：" + String.Format("{0:x2}", data_frame.Cmd);
            OutMsg(richTextBox1, debug_srt, Color.Green);
            Console.WriteLine(debug_srt);
            if ((data_frame.Cmd != 0xc0) || (data_frame.Cmd != 0x88))
            {
                msg_id = attribute_get(data_frame.data_table, data_frame.data_len);
                if (data_frame.Cmd != 0x01)
                {
                    
                    build_ack(clientStream,data_frame, data_frame.Cmd, msg_id);
                    
                }
            }
            else
            {
                ota_data_process(data_frame.Cmd,data_frame.data_table, data_frame.data_len);
            }
        }
        private void ota_data_process(byte cmd,byte[] data,int data_len)
        {
            if (cmd == 0xc0)
            {
                //发送C1下行发送起始包：数据单元为数据包总数+文件总字节数（4字节+4字节）
                send_ota_start_pkg();
            }
            else if(cmd==0x88)
            {
                //上行为升级数据包n请求，下行为升级数据包n，当收到最后一包数据后，发送末包号+1请求，末包号+1即表示接收完毕标识
            }
        }
        int pbar_val = 0;
        int pkgs = 0;
        int remian = 0;
        int pkg_count = 0;
        private long file_len = 0;
        FileStream fsread;
        private void clear_all_data()
        {
            if (fsread != null)
                fsread.Close();
            pbar_val = 0;
            pkgs = 0;
            remian = 0;
            pkg_count = 0;
            file_len = 0;
        }
        private void send_ota_start_pkg()
        {
            if (textBox3.Text == "")
                return;
            clear_all_data();
            FileInfo fi = new FileInfo(textBox3.Text);
            file_len = fi.Length;
            Console.WriteLine(fi.Length);
            fsread = new FileStream(textBox3.Text, FileMode.Open);
            //byte[] heByte = new byte[512];
            //int r = fsread.Read(heByte, 0, heByte.Length);
            pkgs = (int)(file_len / 512);
            remian = (int)(file_len % 512);

            byte[] send_buf = new byte[1024];
            int datalen = 0;
            byte sum = 0;

            send_buf[datalen++] = 0x24;
            send_buf[datalen++] = 0x24;
            send_buf[datalen++] = 0x01;
            send_buf[datalen++] = 0x04;//数据域长度
            send_buf[datalen++] = 0x00;
            send_buf[datalen++] = 0xC1;
            send_buf[datalen++] = (byte)(file_len);
            send_buf[datalen++] = (byte)(file_len >> 8);
            send_buf[datalen++] = (byte)(file_len >> 16);
            send_buf[datalen++] = (byte)(file_len >> 24);
            for (int i = 2; i < datalen; i++)
                sum += send_buf[i];
            send_buf[datalen++] = sum;
            send_buf[datalen++] = 0x35;
            send_buf[datalen++] = 0x35;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            Server_start(textBox1.Text, Convert.ToInt32(textBox2.Text));
        }

        private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
           
            //tcpListener.Stop();
        }

        private void button2_Click(object sender, EventArgs e)
        {

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                System.IO.Path.GetFullPath(openFileDialog1.FileName);                             //绝对路径
                System.IO.Path.GetExtension(openFileDialog1.FileName);                           //文件扩展名
                System.IO.Path.GetFileNameWithoutExtension(openFileDialog1.FileName);//文件名没有扩展  名
                System.IO.Path.GetFileName(openFileDialog1.FileName);                          //得到文件
                System.IO.Path.GetDirectoryName(openFileDialog1.FileName);                  //得到路径
                Console.WriteLine(openFileDialog1.FileName);
                textBox3.Text = openFileDialog1.FileName;


            }
        }
        attribute_structx[] build_att_frame = new attribute_structx[50];
        int build_att_frame_index = 0;
        private void label4_Click(object sender, EventArgs e)
        {
            
        }
        UInt32 data_unit_index = 0;
        byte[] data_unit = new byte[1024];
        private void add_att(UInt16 att_key,string att_val,string att_info)
        {
            UInt32 temp;
            string att_data_str="";
            string debug_str = "";
            string[] ver_str;
            
            
            build_att_frame[build_att_frame_index].att_num = att_key;
            string[] ip_str = new string[4];
            switch (build_att_frame[build_att_frame_index].att_num)
            {
                case 0x02:  //软件版本
                    build_att_frame[build_att_frame_index].att_data = new byte[3];
                    ver_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ver_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ver_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ver_str[0], 10));


                    break;
                case 0x03:  //硬件版本
                    build_att_frame[build_att_frame_index].att_data = new byte[3];
                    ver_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ver_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ver_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ver_str[0], 10));
                    break;
                case 0x04:  //电池电量
                    //temp = Convert.ToUInt16(comboBox4.Text, 32);
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt16(att_val, 10) >> 8);
                    


                    break;
                case 0x05:  //电池电压
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt16(att_val, 10) >> 8);



                    break;
                case 0x06:  //启动类型
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    




                    break;
                
                case 0x11:  //心率
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt16(att_val, 10) >> 8);



                    break;
                case 0x12:  //步数
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt16(att_val, 10) >> 8);

                    

                    break;
                case 0x13:  //定位类型
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt16(att_val, 10));
                    


                    break;
                case 0x15:  //经度
                    build_att_frame[build_att_frame_index].att_data = new byte[12];
                   
                    byte[] lac = gb2312.GetBytes(att_val);
                    for (int i = 0; i < lac.Length; i++)
                    {
                        build_att_frame[build_att_frame_index].att_data[i] = lac[i];
                    }

                    break;
                case 0x17:  //纬度
                    build_att_frame[build_att_frame_index].att_data = new byte[11];
                    byte[] lng = gb2312.GetBytes(att_val);
                    for (int i = 0; i < lng.Length; i++)
                    {
                        build_att_frame[build_att_frame_index].att_data[i] = lng[i];
                    }


                    break;

                case 0x20:  //定位时间
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);
                    break;

                case 0x21:  //上报时间
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);

                    break;

                case 0x22:  //上报频率
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    
                    break;

                case 0x24:  //报警类型
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    
                    break;
                case 0x26:  //充电状态
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                   
                    break;
                case 0x27:  //IP
                    ip_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ip_str[0], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ip_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ip_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(ip_str[3], 10));
                    break;
                case 0x28:  //IP
                    ip_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ip_str[0], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ip_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ip_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(ip_str[3], 10));
                    break;
                case 0x29:  //IP
                    ip_str= att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ip_str[0], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ip_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ip_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(ip_str[3], 10));
                    break;
                case 0x30:  //端口
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    break;
                case 0x34:  //IP
                    ip_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ip_str[0], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ip_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ip_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(ip_str[3], 10));
                    break;
                case 0x35:  //端口
                    build_att_frame[build_att_frame_index].att_data = new byte[2];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    break;
                case 0x36:  //IP
                    ip_str = att_val.Split('.');
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(ip_str[0], 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(ip_str[1], 10));
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(ip_str[2], 10));
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(ip_str[3], 10));
                    break;
                case 0x37:  //自检
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                   
                    break;
                case 0x38:  //设备控制响应
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x31:  //msg_id
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);

                    break;
                case 0x32:  //数据帧状态
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x33:  //ACK命令
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x42:  //UWB定位信息
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);
                    break;
                case 0x43:  //同步时间
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);
                    break;
                case 0x44:  //目标设备类型
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x45:  //UWB工作模式
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x46:  //NFC信息
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data = new byte[4];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));
                    build_att_frame[build_att_frame_index].att_data[1] = (byte)(Convert.ToUInt32(att_val, 10) >> 8);
                    build_att_frame[build_att_frame_index].att_data[2] = (byte)(Convert.ToUInt32(att_val, 10) >> 16);
                    build_att_frame[build_att_frame_index].att_data[3] = (byte)(Convert.ToUInt32(att_val, 10) >> 24);

                    break;
                case 0x50:

                   // byte[] msg_str=Encoding.ASCII.GetBytes(att_val);
                    //Console.WriteLine( ToHexStrFromByte(msg_str,att_val.Length));
                    build_att_frame[build_att_frame_index].att_data = new byte[32];
                    byte[] msg_str = gb2312.GetBytes(att_val);
                    for(int i=0;i< msg_str.Length; i++)
                    {
                        build_att_frame[build_att_frame_index].att_data[i] = msg_str[i];
                    }
                    //Console.WriteLine(ToHexStrFromByte(msg_str, att_val.Length));
                    break;
                case 0x51:  //消息回执
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                case 0x60:  //设备控制
                    build_att_frame[build_att_frame_index].att_data = new byte[1];
                    build_att_frame[build_att_frame_index].att_data[0] = (byte)(Convert.ToUInt32(att_val, 10));

                    break;
                default:
                    break;
            }
            OutMsg(richTextBox2, (build_att_frame_index+1).ToString(), Color.Green);
            debug_str = String.Format("属性ID：{1} @  {0:X2} ", build_att_frame[build_att_frame_index].att_num, att_info);
            Console.WriteLine(debug_str);
            OutMsg(richTextBox2, debug_str, Color.Green);
            data_unit[data_unit_index++] = (byte)build_att_frame[build_att_frame_index].att_num;
            foreach (byte data in build_att_frame[build_att_frame_index].att_data)
            {
                 att_data_str+=(String.Format("{0:X2} ", data));
                data_unit[data_unit_index++] = data;
            };
            debug_str = "属性值：" +att_val +" @ "+att_data_str;
            Console.WriteLine(debug_str);
            OutMsg(richTextBox2, debug_str, Color.Green);
            build_att_frame_index +=1;
        }
        private void button4_Click(object sender, EventArgs e)
        {
            byte frame_start = 0x24;
            byte[] protocol_mode = { 0x24, 0x01 };
            byte[] dev_addr = new byte[4];
            byte dev_mode;
            UInt16 data_lenth;
            byte comond;
            UInt32 check_end = 0;
            byte check_sum=0;
            byte[] end = { 0x35, 0x35 };
            byte[] data_frame = new byte[1024];
            UInt32 index = 0;
            DataRow dr = dt_dev_type.Rows[comboBox2.SelectedIndex];
            Console.WriteLine(dr["类型ID"].ToString());
            dev_mode= (byte)Convert.ToUInt32(dr["类型ID"].ToString(), 16);

            data_frame[index++] = 0x24;
            data_frame[index++] = 0x24;
            data_frame[index++] = 0x01;
            data_frame[index++] = (byte)(Convert.ToUInt32(comboBox1.Text, 10));
            data_frame[index++] = (byte)(Convert.ToUInt32(comboBox1.Text, 10)>>8);
            data_frame[index++] = (byte)(Convert.ToUInt32(comboBox1.Text, 10)>>16);
            data_frame[index++] = (byte)(Convert.ToUInt32(comboBox1.Text, 10)>>24);
            data_frame[index++] = dev_mode;//设备类型
            data_frame[index++] = (byte)(data_unit_index+1);//数据单元长度
            data_frame[index++] = (byte)(data_unit_index>>8);
            data_frame[index++] = (byte)(Convert.ToUInt32(comboBox3.Text, 16));//命令
            data_frame[index++] = (byte)(build_att_frame_index);//属性对个数
            for(int i=0;i< data_unit_index;i++)
            {
                data_frame[index++] = data_unit[i];
            }
            check_end = index;
            for (int k=3;k< check_end;k++)
            {
                check_sum += data_frame[k];
            }
            data_frame[index++] = (byte)(check_sum);
            data_frame[index++] = (byte)(0x35);
            data_frame[index++] = (byte)(0x35);
            string data_frame_str="";
            for(int i=0;i<index;i++)
            {
                data_frame_str += String.Format("{0:X2} ", data_frame[i]);
            }
            Console.WriteLine(data_frame_str);
            OutMsg(richTextBox2 ,"生成数据包:"+data_frame_str,Color.BlueViolet);
            if (data_frame_check(data_frame, (int)index))
            {
                Sever_data_process(null,data_frame, (int)index);
            }
            data_unit_index = 0;
            build_att_frame_index = 0;
            build_att_frame_index = 0;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            DataRow dr = dt_attr.Rows[comboBox4.SelectedIndex];
            Console.WriteLine(dr["属性ID"].ToString());
            add_att(Convert.ToUInt16(dr["属性ID"].ToString(), 16),textBox4.Text,comboBox4.Text);
        }

        private void button5_Click(object sender, EventArgs e)
        {
            Form5 f5 = new Form5();
            //f2.MdiParent = this;
            f5.Show();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            data_unit_index = 0;
            build_att_frame_index = 0;
            build_att_frame_index = 0;
            richTextBox2.Clear();
        }
    }
}
